package com.chapter.sample.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自选锁案例
 */
public class SpinLockDemo {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();
    public void lock() {//加锁
        System.out.println(Thread.currentThread().getName() + "..... come in");
        //atomicReference.compareAndSet(null, Thread.currentThread())
        // true持有锁成功（占用成功）；“取反” = false；退出while 持有锁的线程“成功”，不用等待
        // false加锁失败（占用失败）；“取反” = true；进入 while 内，不停询问 “while结果”，进入while
        while (!atomicReference.compareAndSet(null, Thread.currentThread())) {
            System.out.println(Thread.currentThread().getName() + "..... 持有锁");
        }
        System.out.println(Thread.currentThread().getName() + "..... 持有锁成功 in");
    }
    public void unLock() {
        atomicReference.compareAndSet(Thread.currentThread(), null);
        System.out.println(Thread.currentThread().getName() + "..... 释放锁成功");
    }
    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo spinLock = new SpinLockDemo();
        new Thread(() ->{
            spinLock.lock();
            //业务处理
            try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {throw new RuntimeException(e);}
            spinLock.unLock();
        },"t1").start();
        new Thread(()->{
            spinLock.lock();
            spinLock.unLock();
        },"t2").start();
    }

}
